package com.superpeer.baseproject.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.superpeer.baseproject.wight.CustomDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class DownLoadImgUtils {

    public static void downLoadImage(Context context,String imageUrl,String name){
        initPermissions(context, new GrantedCallBack() {
            @Override
            public void callBack(List<String> permissions, boolean all) {
                Glide.with(context).asBitmap().load(imageUrl).addListener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable @org.jetbrains.annotations.Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                savePicture(context,resource,name);
                            }
                        });
                        return false;
                    }
                }).submit();
            }
        });
    }

    public static void savePicture(Context context,Bitmap bitmap,String name){
        initPermissions(context, new GrantedCallBack() {
            @Override
            public void callBack(List<String> permissions, boolean all) {
                try {
                    String savePath = null;
                    String fileName = name + ".JPEG";
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        savePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/兔兔/";
                    } else {
                        Toast.makeText(context, "保存失败！", Toast.LENGTH_SHORT).show();
                    }
                    File filePic = new File(savePath + fileName);
                    if (!filePic.exists()) {
                        filePic.getParentFile().mkdirs();
                        filePic.createNewFile();
                    }
                    FileOutputStream fos = new FileOutputStream(filePic);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();

                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + savePath+fileName)));
                    Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void savePicture(Context context,View view,String name){
        savePicture(context,BitmapUtil.createViewBitmap(view),name);
    }

    private static void initPermissions(Context context, GrantedCallBack grantedCallBack) {
        XXPermissions.with(context)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(null != grantedCallBack){
                            grantedCallBack.callBack(permissions,all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            CustomDialog customDialog = new CustomDialog(context);
                            customDialog.setMessage("获取权限失败，保存图片功能无法正常使用，请到权限设置页面，开启权限");
                            customDialog.setNegativeButton("取消",null);
                            customDialog.setPositiveButton("去设置", new CustomDialog.OnPositiveClickListener() {
                                @Override
                                public void click(CustomDialog dialog) {
                                    XXPermissions.startPermissionActivity(context, permissions);
                                }
                            });
                            customDialog.show();
                        }
                    }
                });
    }

    private interface GrantedCallBack{
        void callBack(List<String> permissions, boolean all);
    }
}
